/*-------- prodct details slider active start --------*/
/* */
function upDateSlide() {
    $('.product-large-slider').slick({
        fade: true,
        arrows: false,
        asNavFor: '.pro-nav'
    });

    // product details slider nav active
    $('.pro-nav').slick({
        slidesToShow: 4,
        asNavFor: '.product-large-slider',
        centerMode: true,
        centerPadding: 0,
        focusOnSelect: true,
        prevArrow: '<button type="button" class="slick-prev"><i class="lnr lnr-chevron-left"></i></button>',
        nextArrow: '<button type="button" class="slick-next"><i class="lnr lnr-chevron-right"></i></button>',
        responsive: [{
            breakpoint: 576,
            settings: {
                slidesToShow: 3,
                arrows: false
            }
        }]
    });

    /*-------- prodct details slider active end --------*/

    $('.product-carousel--4').slick({
        autoplay: false,
        fade: false,
        speed: 1000,
        slidesToShow: 4,
        adaptiveHeight: true,
        prevArrow: '<button type="button" class="slick-prev"><i class="lnr lnr-chevron-left"></i></button>',
        nextArrow: '<button type="button" class="slick-next"><i class="lnr lnr-chevron-right"></i></button>',
        responsive: [{
                breakpoint: 992,
                settings: {
                    slidesToShow: 3
                }
            },
            {
                breakpoint: 768,
                settings: {
                    slidesToShow: 2
                }
            },
            {
                breakpoint: 480,
                settings: {
                    slidesToShow: 1
                }
            }
        ]
    });

}

/**
 * 获取iid
 */
function getIid() {
    const url = location.href
    const urlObj = new URL(url)
    const searchParams = urlObj.searchParams
    return searchParams.get('iid')
}
let goodsDetail;
//根据iid请求网络并渲染页面
function getGoodsDetail(iid) {
    ajax({
        url: "http://123.207.32.32:8000/api/m3/detail",
        data: {
            iid
        },
        success(res) {
            // console.log(res)
            goodsDetail = res.result
            renderGoodsInfo(res.result)
            renderDescription(res.result)
            renderParams(res.result)
            renderReviews(res.result)

        }
    })
}

const iid = getIid()
getGoodsDetail(iid)


//生成商品简介信息html
function genGoodsInfoHtml(goodsData) {
    return ` 
        <div class="product-details-des">
        <h3 class="product-name">${goodsData.itemInfo.title}</h3>
        <div class="ratings d-flex">
            <span><i class="lnr lnr-star"></i></span>
            <span><i class="lnr lnr-star"></i></span>
            <span><i class="lnr lnr-star"></i></span>
            <span><i class="lnr lnr-star"></i></span>
            <span><i class="lnr lnr-star"></i></span>
            <div class="pro-review">
                <span>${goodsData.rate.cRate} 评论</span>
            </div>
        </div>
        <div class="price-box">
            <span class="price-regular">${goodsData.itemInfo.price}</span>
            <span class="price-old"><del>￥${goodsData.itemInfo.highPrice}</del></span>
        </div>
       
        <div class="availability">
            <i class="fa fa-check-circle"></i>
            <span>库存${goodsData.skuInfo.totalStock}</span>
        </div>
        <p class="pro-desc">${goodsData.itemInfo.desc}</p>
        <div class="quantity-cart-box d-flex align-items-center">
            <h5>购买数量:</h5>
            <div class="quantity">
                <div class="pro-qty"><input type="text" value="1"></div>
            </div>
            <div class="action_link">
                <a class="btn btn-cart2" href="#">添加到购物车</a>
            </div>
        </div>
        <div class="pro-size">
            <h5>size :</h5>
            <select class="nice-select">
                <option>S</option>
                <option>M</option>
                <option>L</option>
                <option>XL</option>
            </select>
        </div>
        <div class="color-option">
            <h5>color :</h5>
            <ul class="color-categories">
                <li>
                    <a class="c-lightblue" href="#" title="LightSteelblue"></a>
                </li>
                <li>
                    <a class="c-darktan" href="#" title="Darktan"></a>
                </li>
                <li>
                    <a class="c-grey" href="#" title="Grey"></a>
                </li>
                <li>
                    <a class="c-brown" href="#" title="Brown"></a>
                </li>
            </ul>
        </div>
        <div class="useful-links">
            <a href="#" data-toggle="tooltip" title="Compare"><i
                    class="lnr lnr-sync"></i>比较</a>
            <a href="#" data-toggle="tooltip" title="Wishlist"><i
                    class="lnr lnr-heart"></i>收藏</a>
        </div>
        <div class="like-icon">
            <a class="facebook" href="#"><i class="fa fa-facebook"></i>like</a>
            <a class="twitter" href="#"><i class="fa fa-twitter"></i>tweet</a>
            <a class="pinterest" href="#"><i class="fa fa-pinterest"></i>save</a>
            <a class="google" href="#"><i class="fa fa-google-plus"></i>share</a>
        </div>
    </div>`
}
//生成商品轮播图html
function genLargeSliderHtml(goodsData) {
    const imgHtmlArr = goodsData.itemInfo.topImages.map(item => {
        return `<div class="pro-large-img img-zoom">
            <img src="${item}" alt="product-details" />
        </div>`
    })
    return ` 
    <div class="product-large-slider">
       ${imgHtmlArr.join('')}
    </div>`
}
//生成商品轮播图导航图示html
function genProNavHtml(goodsData) {
    const imgHtmlArr = goodsData.itemInfo.topImages.map(item => {
        return `
        <div class="pro-nav-thumb">
            <img src="${item}" alt="product-details" />
        </div>`
    })
    return `<div class="pro-nav slick-row-10 slick-arrow-style">
        ${imgHtmlArr.join('')}
    </div>`
}

//渲染商品简介信息
function renderGoodsInfo(goodsData) {
    const sliderCon = document.querySelector('.slider-con')
    sliderCon.innerHTML = genLargeSliderHtml(goodsData) + genProNavHtml(goodsData)

    const goodsInfoCon = document.querySelector('.goods-info')
    goodsInfoCon.innerHTML = genGoodsInfoHtml(goodsData)
    upDateSlide()
    bindAddToCart()

}

function renderDescription(goodsData) {
    const imgList = goodsData.detailInfo.detailImage[0].list
    const imgListHtmlArr = imgList.map(item => {
        return `<img src=${item} />`
    })
    const con = document.querySelector('.tab-one')
    con.innerHTML = imgListHtmlArr.join()
}

function renderParams(goodsData) {
    const con = document.querySelector('.goods-params tbody')
    const params = goodsData.itemParams.info.set
    const arr = params.map(item => {
        return `
        <tr>
            <td>${item.key}</td>
            <td>${item.value}</td>
        </tr>`
    })
    con.innerHTML = arr.join('')

}

function renderReviews(goodsData) {

    const con = document.querySelector('.review-con')
    const reviews = goodsData.rate.list
    const score = Math.ceil(Math.random() * 5)
    const arr = reviews.map(item => {
        return `
        <div class="total-reviews">
            <div class="rev-avatar">
                <img src="${item.user.avatar}" alt="">
            </div>
            <div class="review-box">
                <div class="ratings">
                    ${genStar(score)}
                </div>
                <div class="post-author">
                    <p><span>${item.user.uname}</span> ${formatTime(item.created)}</p>
                </div>
                <p>${item.content}</p>
                <p>${item.explain || ''}</p>
            </div>
        </div>`
    })
    con.innerHTML = `<h5>评论数量 <span>${goodsData.rate.cRate}</span></h5>` + arr.join('')
}

function formatTime(stamp) {
    const date = new Date(stamp * 1000)
    return date.toLocaleDateString() + "  " + date.toLocaleTimeString()
}

function genStar(num) {
    return new Array(num).fill().map(item => {
        return ' <span class="good"><i class="fa fa-star"></i></span>'
    }).join('')

}

//添加到购物车
function addToCart(num) {
    if(!goodsDetail){
        alert('数据获取失败')
        return 
    }
    const cartItem = {
        iid: goodsDetail.itemInfo.iid,
        img: goodsDetail.itemInfo.topImages[0],
        num,
        price: goodsDetail.itemInfo.lowNowPrice,
        title: goodsDetail.itemInfo.title,
    }
    console.log(cartItem)
    cart.addToCart(cartItem)
}

function bindAddToCart(){
    const numIpt = document.querySelector('.pro-qty>input')
    const btn = document.querySelector('.btn-cart2')
    btn.onclick = function(){
        const num = numIpt.value
        addToCart(num)
    }
}